package cn.xiaoliu.org.service.impl;

import cn.xiaoliu.basic.service.impl.BaseServiceImpl;
import cn.xiaoliu.basic.utils.MD5Utils;
import cn.xiaoliu.basic.utils.StrUtils;
import cn.xiaoliu.org.domain.Employee;
import cn.xiaoliu.org.mapper.EmployeeMapper;
import cn.xiaoliu.org.service.IEmployeeService;
import cn.xiaoliu.user.domain.Logininfo;
import cn.xiaoliu.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    //1.基本的CRUD通过继承得到

    //2.扩展的业务方法实现,自己在这里添加

    //需要级联处理Logininfo信息，要改一起改
    @Override
    public void add(Employee employee) {
        initEmployee(employee);//设置employee必要的参数：盐值和密码
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        super.add(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        //按照相同的名字拷贝属性
        BeanUtils.copyProperties(employee,logininfo );
        logininfo.setType(0);//注意（一定要设置）前端用户注册
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        //密码
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }
}
